package com.hdl.mapper;

import com.hdl.pojo.Order;
import com.hdl.pojo.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.cache.impl.PerpetualCache;
import org.mybatis.caches.redis.RedisCache;

import java.util.List;

/**
 * 接口名 IUserMapper
 * 描述 用户持久层接口
 *
 * @author hedonglin
 * @version 1.0
 * @date 2020/4/22 20:29
 */
//@CacheNamespace(implementation = PerpetualCache.class)// 开启二级缓存，默认实现PerpetualCache
@CacheNamespace(implementation = RedisCache.class)// 开启二级缓存，使用Redis实现
public interface IUserMapper {
    /**
     * 查询所有用户
     */
    @Select("select * from user")
    List<User> findAll();

    /**
     * 新增用户
     */
    @Insert("insert into user(id, username, password, birthday) values(#{id}, #{username}, #{password}, #{birthday})")
    void insertUser(User user);

    /**
     * 修改用户
     */
    @Update("update user set username = #{username} where id = #{id}")
    void updateUser(User user);

    /**
     * 删除用户
     */
    @Delete("delete from user where id = #{id}")
    void deleteUser(Integer id);

    /**
     * 根据id查询用户信息
     */
//    @Options(useCache = false)// 禁用二级缓存
    @Select("select * from user where id = #{id}")
    User findUserById(Integer id);


    /**
     * 根据用户查询用户关联的订单（一对多查询）
     */
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "password", column = "password"),
            @Result(property = "birthday", column = "birthday"),
            @Result(property = "orders", column = "id",
                    many = @Many(select = "com.hdl.mapper.IOrderMapper.findOrderByUserId")),
    })
    @Select("select * from user where id = #{id}")
    User findUserAndOrder(Integer id);


    /**
     * 根据用户查询角色，多对多查询
     */
    /**
     * 根据用户查询用户关联的订单（一对多查询）
     */
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "password", column = "password"),
            @Result(property = "birthday", column = "birthday"),
            @Result(property = "orders", column = "id",
                    many = @Many(select = "com.hdl.mapper.IOrderMapper.findOrderByUserId")),
            @Result(property = "roles", column = "id",
                    many = @Many(select = "com.hdl.mapper.IRoleMapper.findRoleByUserId")),
    })
    @Select("select * from user where id = #{id}")
    User findUserAndRole(Integer id);
}
